package com.hua.server.oauth.config.security.service;

import com.google.common.collect.Lists;
import com.hua.server.oauth.domain.UserRepository;
import com.hua.server.oauth.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 基于RBAC自定义认证实现
 *
 * @author 华云龙
 * @date 2019-5-27
 */
@Slf4j
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        //noinspection MismatchedQueryAndUpdateOfCollection
        List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
        if (null != user) {
            userRepository.findById(user.getId()).ifPresent(u -> u.getRoles().forEach(role -> {
                role.getPermissions().forEach(permission -> {
                    if (permission != null && permission.getEnName() != null) {
                        grantedAuthorities.add(new SimpleGrantedAuthority(permission.getEnName()));
                    }
                });
            }));
            log.debug("姓名:{},权限:{}", username, grantedAuthorities);
            return new org.springframework.security.core.userdetails.User(username, user.getPassword(), grantedAuthorities);
        }
        log.debug("登录失败!登录用户名:{}", username);
        return null;
    }
}
